//
//  LoginViewController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/29.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "HomePageController.h"
#import "OrderViewController.h"
#import "MineViewController.h"

@interface LoginViewController ()
@property (strong, nonatomic) IBOutlet UIButton *loginButton;
@property (strong, nonatomic) IBOutlet UIImageView *mobileView;
@property (strong, nonatomic) IBOutlet UIImageView *passWordView;
@property (strong, nonatomic) IBOutlet UITextField *mobileTextField;
@property (strong, nonatomic) IBOutlet UITextField *passWordTextField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    __weak typeof(self)weakSelf = self;
    [self addLeftButtonWithImage:nil actionBlock:^{
        
    }];
    [self addRightButtonWithTitle:@"快速注册" actionBlock:^{
        RegisterViewController *registerVC = [[RegisterViewController alloc]init];
        registerVC.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:registerVC animated:YES];
        
    }];
    self.loginButton.layer.cornerRadius = self.mobileView.layer.cornerRadius = self.passWordView.layer.cornerRadius = 5.0f;
    self.loginButton.layer.masksToBounds = self.mobileView.layer.masksToBounds = self.passWordView.layer.masksToBounds = YES;
    self.mobileTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
}


- (void)viewWillDisappear:(BOOL)animated
{
    [self.mobileTextField resignFirstResponder];
    [self.passWordTextField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.mobileTextField resignFirstResponder];
    [self.passWordTextField resignFirstResponder];
}

// 登录按钮
- (IBAction)loginButtonAction:(UIButton *)sender {
    BOOL isMatchTwo = [self isValidateMobile:self.mobileTextField.text];
    
    if ([self.mobileTextField.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码！"];
    }else if (!isMatchTwo || self.mobileTextField.text.length <11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码！"];
    }
    else if ([self.mobileTextField.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入密码！"];
    }else
    {
        [self webRequest_Login:self.mobileTextField.text setpassword:self.passWordTextField.text];
    }
}

- (void)webRequest_Login:(NSString *)username setpassword:(NSString *)password
{
    [self.mobileTextField resignFirstResponder];
    [self.passWordTextField resignFirstResponder];
    NSDictionary *dict =  @{@"mobile":username,@"password":password};
//    [SVProgressHUD show];
    [HttpRequestManager postMethod:KLoginInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if ([[response[@"status"] stringValue] isEqualToString:@"1"]) {
            [[NSUserDefaults standardUserDefaults]setObject:response[@"uid"] forKey:KUserDefaultsUserIdKey];
            [[NSUserDefaults standardUserDefaults] setObject:self.mobileTextField.text forKey:KUserDefaultsUserMobileNO];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            HomePageController *homePageVC = [[HomePageController alloc]init];
            homePageVC.title = @"抢单";
            homePageVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:homePageVC.title image:[UIImage imageNamed:@"抢单"] selectedImage:[UIImage imageNamed:@"抢单选中"]];
            BaseNavController *homePageNav = [[BaseNavController alloc] initWithRootViewController:homePageVC];
            
            OrderViewController *orderVC = [[OrderViewController alloc]init];
            orderVC.title = @"我的订单";
            orderVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:orderVC.title image:[UIImage imageNamed:@"我的订单"] selectedImage:[UIImage imageNamed:@"我的订单选中"]];
            BaseNavController *orderNav = [[BaseNavController alloc] initWithRootViewController:orderVC];
            
            MineViewController *mineVC = [[MineViewController alloc]init];
            mineVC.title = @"我的";
            mineVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:mineVC.title image:[UIImage imageNamed:@"我的"] selectedImage:[UIImage imageNamed:@"我的选中"]];
            BaseNavController *mineNav = [[BaseNavController alloc] initWithRootViewController:mineVC];
            
            // tab bar
            UITabBarController *rootTabBarController = [[UITabBarController alloc] init];
//            [rootTabBarController.navigationController setNavigationBarHidden:NO animated:NO];
            rootTabBarController.viewControllers = @[homePageNav,orderNav,mineNav];
//            HomePageController *homePageVC = [[HomePageController alloc]init];
            [self presentViewController:rootTabBarController animated:YES completion:^{
                
            }];
//            [self.navigationController pushViewController:rootTabBarController animated:YES];
//            [self.navigationController popViewControllerAnimated:YES];
            
        }else if ([[response[@"status"] stringValue] isEqualToString:@"2"]) {
            [[[UIAlertView alloc] initWithTitle:nil message:@"请审核通过以后再登录!" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil] show];
        }else{
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
        }
    }];
}

// 忘记密码按钮
- (IBAction)forgetPasswordButtonAction:(UIButton *)sender {
    ForgetViewController *forgetVC = [[ForgetViewController alloc]init];
    [self.navigationController pushViewController:forgetVC animated:YES];
    
}

-(BOOL) isValidateMobile:(NSString *)mobile
{
    if (mobile.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobile] == YES)
        || ([regextestcm evaluateWithObject:mobile] == YES)
        || ([regextestct evaluateWithObject:mobile] == YES)
        || ([regextestcu evaluateWithObject:mobile] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
